<?php
use think\Log;
class Alipay
{
    public $alipay_config = array(
        //appid
        'appid' => '',
        //商户密钥
        'rsaPrivateKey' => '',//私钥
        //支付宝公钥
        'alipayrsaPublicKey' => '',//公钥(自己的程序里面用不到)
        'partner' => '',//(商家的参数,新版本的好像用不到)
        'input_charset' => 'utf-8',//编码
        'notify_url' => '',//回调地址(支付宝支付成功后回调修改订单状态的地址)
        'payment_type' => 1,//(固定值)
        'seller_id' => '',//合作伙伴身份（PID）
        'charset' => 'utf-8',//编码
        'sign_type' => 'RSA2',//签名方式
        'timestamp' => '',
        'version' => "1.0",//固定值
        'url' => 'https://openapi.alipay.com/gateway.do',//固定值
        'method' => 'alipay.trade.app.pay',//固定值
    );

    function __construct($params = [])
    {
        $this->alipay_config['timestamp'] = date("Y-m-d H:i:s");
        $this->alipay_config['seller_id'] = $params['alipay_partner'];
        $this->alipay_config['appid'] = $params['alipay_appid'];
        $this->alipay_config['rsaPrivateKey'] = $params['alipay_rsaPrivateKey'];
        $this->alipay_config['notify_url'] = $params['notify_url'];
        $this->alipay_config['alipayrsaPublicKey'] = $params['alipay_alipayrsaPublicKey'];
    }

    //生成提交支付宝参数数组
    public function createAppPara($params = array())
    {
        $body = '';
        $body .= 'orderType=' . $params['orderType'];//订单类型 material 是实物订单 pdr_order 是充值
        $body .= '&payType=' . $params['payType']; //类型order_sn 或者pay_sn
        $decoded_user_token = decoded_user_token($params['user_token']);
        $body .= "&member_id=" . $decoded_user_token['data']->member_id;;
        //构造业务请求参数的集合(订单信息)
        $content = array();
        $content['subject'] = $params['subject'];//商品的标题/交易标题/订单标题/订单关键字等
        $content['out_trade_no'] = $params['out_trade_no'];//商户网站唯一订单号
//         $content['body'] = $body;//商户网站唯一订单号
        $content['passback_params'] = urlencode($body);//商户网站唯一订单号
        $content['timeout_express'] = '1d';//该笔订单允许的最晚付款时间
        $content['total_amount'] = floatval($params['price']);//订单总金额(必须定义成浮点型)
        $content['product_code'] = 'QUICK_MSECURITY_PAY';//销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
        // $content['store_id'] = 'BJ_001';//商户门店编号
        $con = json_encode($content);//$content是biz_content的值,将之转化成字符串
        //公共参数
        $param = array();
        require_once "AopClient.php";
        require_once "request/AlipayTradeAppPayRequest.php";
        $aop = new AopClient();
        $aop->appId = $this->alipay_config['appid'];
        $aop->rsaPrivateKey = $this->alipay_config['rsaPrivateKey'];
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = $this->alipay_config['alipayrsaPublicKey'];
//        var_dump( $this->alipay_config);exit();
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        $request = new AlipayTradeAppPayRequest();
//SDK已经封装掉了公共参数，这里只需要传入业务参数
        $request->setNotifyUrl($this->alipay_config['notify_url']);
        $request->setBizContent($con);
//这里和普通的接口调用不同，使用的是sdkExecute
        $response = $aop->sdkExecute($request);
//        var_dump($response);exit();
//htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
//        $response = str_replace('alipay_sdk=alipay-sdk-php-20180705&','',$response);
        return $response;
    }

    public function alipayRefund($param)
    {
        require_once "AopClient.php";
        require_once "request/AlipayTradeRefundRequest.php";
        $request = new AlipayTradeRefundRequest ();
        $aop = new AopClient();
        $aop->appId =$this->alipay_config['appid'];
        $aop->rsaPrivateKey = $this->alipay_config['rsaPrivateKey'];
        $aop->format = "json";
        $aop->charset = "UTF-8";
        $aop->signType = "RSA2";
        $aop->alipayrsaPublicKey = $this->alipay_config['alipayrsaPublicKey'];
        $bizcontent = json_encode([
            'out_trade_no' =>empty($param['out_trade_no'])?'':$param['out_trade_no'],
            'trade_no' =>empty($param['trade_no'])?'':$param['trade_no'],
            'refund_amount' =>$param['refund_amount'],
            'refund_reason' =>empty($param['refund_reason'])?'普通退款':$param['refund_reason'],
        ]);
        $request->setBizContent($bizcontent);
        $result = $aop->execute($request);
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
//        $resultData['buyer_logon_id'] = $result->$responseNode->buyer_logon_id;
        $resultData['code'] = $result->$responseNode->code;
        $resultData['msg'] = $result->$responseNode->msg;
//        $resultData['gmt_refund_pay'] = $result->$responseNode->gmt_refund_pay;
//        $resultData['refund_fee'] = $result->$responseNode->refund_fee;
//        $resultData['trade_no'] = $result->$responseNode->trade_no;
//        $resultData['out_trade_no'] = $result->$responseNode->out_trade_no;
        return $resultData;


    }

    public function rsaCheck()
    {
        require_once "AopClient.php";
        $Client = new AopClient();//实例化支付宝sdk里面的AopClient类,下单时需要的操作,都在这个类里面
        $Client->alipayrsaPublicKey = $this->alipay_config['alipayrsaPublicKey'];
        return $Client->rsaCheckV1($_POST, '', 'RSA2');
    }

}

?>